﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Configuration;
using System.IO;
using System.Xml.Serialization;
using System.Security.Cryptography;
using System.Windows.Forms;
using BWClient.BWServiceReference;
using DevComponents.DotNetBar;

using MSXML;
using System.ServiceModel.Configuration;

namespace BWClient
{
    public class CommonHelper
    {
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="oString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string DESDecode(string oString, string decryptKey)
        {
            try
            {
                decryptKey = decryptKey.Substring(0, 8);
                decryptKey = decryptKey.PadRight(8, ' ');
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//默认密钥向量
                byte[] inputByteArray = Convert.FromBase64String(oString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return "";
            }
        }

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
        public static string DESEncode(string encryptString, string encryptKey)
        {
            encryptKey = encryptKey.Substring(0, 8);
            encryptKey = encryptKey.PadRight(8, ' ');
            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//默认密钥向量
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());

        }

        /// <summary>
        /// 验证webservice地址是否正常
        /// </summary>
        /// <returns></returns>
        public static bool CheckWebServiceStatus()
        {
            string strURL = string.Empty;
            ClientSection oClientSection = System.Configuration.ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
            foreach (ChannelEndpointElement item in oClientSection.Endpoints)
            {
                if (item.Name == "bwserviceSoap")
                    strURL = item.Address.ToString();
            }

            if (string.IsNullOrEmpty(strURL))
            {
                MessageBoxEx.Show("无法读取webservice地址，请重新配置！");
                Application.Exit();
            }

            XMLHTTPRequest http = new XMLHTTPRequest();
            try
            {
                http.open("GET", strURL, false, null, null);
                http.send(null);
                int iStatus = http.status;
                //如果取得的网页状态不正确,   就是不存在或没权访问   
                if (iStatus == 200 || iStatus == 0)
                    return true;
                else
                {
                    MessageBoxEx.Show("读取webservice发生错误，请重新配置！");
                    return false;
                }
            }
            catch (Exception oEX)
            {
                MessageBoxEx.Show(oEX.Message);
                MessageBoxEx.Show("读取webservice发生错误，请重新配置！");
                return false;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="strUsername"></param>
        /// <param name="strPassword"></param>
        /// <param name="bIsSaveFile"></param>
        /// <returns></returns>
        public static UserLoginResult UserLogin(string strUsername, string strPassword, bool bIsSaveFile, ref int iUserID)
        {
            iUserID = 0;

            int iLoginResult = 0;

            try
            {
                bwserviceSoapClient m_WebService = new bwserviceSoapClient();
                if (CheckWebServiceStatus() == false)
                    return UserLoginResult.WebServiceError;
                iLoginResult = m_WebService.UserLogin(strUsername, strPassword);
            }
            catch(Exception oEX)
            {
                MessageBoxEx.Show(oEX.Message);
                MessageBoxEx.Show("用户自动登陆时服务器验证地址出错，请重新配置，软件将自动关闭。");
                return UserLoginResult.WebServiceError;
            }

            if (iLoginResult < 0)
            {
                MessageBoxEx.Show("登录失败，您的帐户或密码输入错误！");
                return UserLoginResult.UserPwdError;
            }
            else
            {
                if (bIsSaveFile)
                {
                    //保存文件
                    BWClientData oBWClientData = BWClientDataManager.getCurrentBWClientData();
                    oBWClientData.UserName = strUsername;
                    oBWClientData.Password = DESEncode(strPassword, BWClientDataManager.DesKey);
                    oBWClientData.AutoLogin = true;
                    oBWClientData.iUserID = iLoginResult;
                    SerializationHelper.Save(oBWClientData, BWClientDataManager.FileName);
                }
                iUserID = iLoginResult;
                return UserLoginResult.LogonOK;
            }
        }

        public enum UserLoginResult
        {
            WebServiceError = 1,
            LogonOK = 2,
            UserPwdError = 3
        }
    }
}
